package org.rency.crawler.fetch.handler.impl;

import java.util.HashSet;
import javax.annotation.Resource;
import org.rency.crawler.common.exception.CrawlerException;
import org.rency.crawler.domain.queue.FetchQueue;
import org.rency.crawler.domain.state.FetchStatus;
import org.rency.crawler.domain.vo.DocDomain;
import org.rency.crawler.fetch.handler.AbstractFetchHandler;
import org.rency.crawler.fetch.helper.BuilderHelper;
import org.rency.crawler.fetch.helper.FetchCarrier;
import org.rency.crawler.fetch.service.parser.ParserService;
import org.springframework.stereotype.Component;

/**
 * 名称:FetchParseHandler
 * 描述:${TODO}
 *
 * @author:rency
 * @version:V1.0.0
 * @JDK 1.8
 * @since 2017/11/22 21:54
 */
@Component
public class FetchParseHandler extends AbstractFetchHandler{

  @Resource
  private ParserService parserService;

  @Override
  protected String getHandlerName() {
    return "内容解析";
  }

  @Override
  protected void onHandler(FetchCarrier carrier) throws CrawlerException {
    HashSet<FetchQueue> fetchQueueCollection = new HashSet<FetchQueue>();
    //只会有一个元素
    HashSet<DocDomain> docQueueCollection = new HashSet<DocDomain>();
    carrier.setFetchQueueCollection(fetchQueueCollection);
    carrier.setDocQueueCollcetion(docQueueCollection);

    //避免再次抓取当前目标
    fetchQueueCollection.add(BuilderHelper.build(carrier));
    if(carrier.getHttpResponse().isFile()){
      docQueueCollection.add(BuilderHelper.build(carrier.getRequest().getFetchNo(), carrier.getRequest().getFetchUri(), null, null, null, carrier.getHttpResponse().getCharset(), carrier.getHttpResponse().getContent(), carrier.getHttpResponse().getContent()));
    }else {
      this.parserService.parser(carrier, fetchQueueCollection, docQueueCollection);
    }
    carrier.getFetchState().setFsStatus(FetchStatus.SUCCESS);
  }
}
